package com.qf.shop.order.listener;

import com.qf.shop.common.constants.OrderConstatns;
import com.qf.shop.common.vo.StockVo;
import com.qf.shop.order.entity.OrderEntity;
import com.qf.shop.order.feign.api.StockService;
import com.qf.shop.order.service.OrderService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

@Component
@Slf4j
public class OrderTtlDleListener {

    @Autowired
    private OrderService orderService;

    @Autowired
    private StockService stockService;

    // 这个方法被调用说明订单已经到3m
    @RabbitListener(queues = OrderConstatns.ORDER_TTL_DLE_QUEUE)
    public void orderTimeout(String orderId, Channel channel, Message message) {
        try {

            // 1.查询订单的最新状态
            OrderEntity orderEntity = orderService.getOrderById(orderId);

            // 2.判断订单的状态
            if (orderEntity.getStatus() == 1) { // 3m之后还是未支付，需要修改订单状态为已超时

                orderService.updateOrderStatus(orderId, 4);

                // 通知支付宝把交易订单关闭
            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    // 这个方法被调用说明订单已经到3m
    @RabbitListener(queues = OrderConstatns.STOCK_DLE_UNLOCK_QUEUE)
    public void stockUnlock(String orderId, Channel channel, Message message) {
        try {
            // 1.查询订单的最新状态
            OrderEntity orderEntity = orderService.getOrderById(orderId);

            // 2.判断订单的状态
            if (orderEntity.getStatus() == 4 || orderEntity.getStatus() == 3) { // 3m之后还是未支付，需要修改订单状态为已超时

                // 3.查询订单详情
                List<StockVo> stockVoList = orderService.getStockVoListOrderId(orderId);

                if (stockVoList != null && !stockVoList.isEmpty()) {
                    log.debug("库存释放了。。{}",stockVoList);
                    // 4.释放库存
                    stockService.unLockStock(stockVoList);
                }
                // 通知支付宝把交易订单关闭
            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
